package com.medical.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.medical.mapper.SysRoleMapper;
import com.medical.model.*;
import com.medical.service.SysUserRoleService;
import com.medical.mapper.SysUserRoleMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author ziluolan
 * @description 针对表【sys_user_role】的数据库操作Service实现
 * @createDate 2023-05-09 21:34:22
 */
@Service
public class SysUserRoleServiceImpl extends ServiceImpl<SysUserRoleMapper, SysUserRole>
        implements SysUserRoleService {
    @Resource
    SysUserRoleMapper sysUserRoleMapper;
    @Resource
    SysRoleMapper sysRoleMapper;
    /**
     * 设置默认角色关联中间表
     */
    @Override
    public void setDefaultRole(SysUser sysUser) {
        SysUserRole sysUserRole = new SysUserRole();
        sysUserRole.setUserId(Long.valueOf(sysUser.getUserId()));
        sysUserRole.setRoleId(sysRoleMapper.selectOne(new QueryWrapper<SysRole>().eq("code", "common")).getId());//查询普通用户角色的id
        sysUserRoleMapper.insert(sysUserRole);
    }
    /**
     * 修改用户对应的角色通过用户id
     */
    @Override
    public int updateUserRole(List<SysRole> sysRoles, Long id) {
        int update=0;
        List<SysUserRole> sysUserRoles = sysUserRoleMapper.selectList(new QueryWrapper<SysUserRole>().eq("user_id", id));
        for (SysUserRole userRole : sysUserRoles) {
            sysUserRoleMapper.delete(new QueryWrapper<SysUserRole>().eq("user_id", userRole.getUserId()));
        }
        for (SysRole tem : sysRoles) {
            int insert = sysUserRoleMapper.insert(new SysUserRole(null, id, tem.getId()));
            update+=insert;

        }
        return update;

    }
}




